{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 关于参数（下）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 可以接收一系列值的位置参数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果你在定义参数的时候，在一个*位置参数*（Positional Arguments）前面标注了星号，`*`，那么，这个位置参数可以接收一系列值，在函数内部可以对这一系列值用 `for ... in ...` 循环进行逐一的处理。\n",
    "\n",
    "带一个星号的参数，英文名称是 “Arbitrary Positional Arguments”，姑且翻译为 “随意的位置参数”。\n",
    "\n",
    "还有带两个星号的参数，一会儿会讲到，英文名称是 “Arbitrary Keyword Arguments”，姑且翻译为 “随意的关键字参数”。\n",
    "\n",
    "> 有些中文书籍把 “Arbitrary Positional Arguments” 翻译成 “可变位置参数”。事实上，在这样的地方，无论怎样的中文翻译都是令人觉得非常吃力的。前面的这个翻译还好了，我还见过把 “Arbitrary Keyword Arguments” 翻译成 “武断的关键字参数” 的 —— 我觉得这样的翻译肯定会使读者产生说不明道不白的疑惑。\n",
    ">\n",
    "> 所以，**入门之后就尽量只用英文**是个好策略。虽然刚开始有点吃力，但后面会很省心，很长寿 —— 是呀，少浪费时间、少浪费生命，其实就相当于更长寿了呀！"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi, ann!\n",
      "Hi, mike!\n",
      "Hi, john!\n",
      "Hi, zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(*names):\n",
    "    for name in names:\n",
    "        print(f'Hi, {name}!')\n",
    "say_hi()\n",
    "say_hi('ann')\n",
    "say_hi('mike', 'john', 'zeo')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`say_hi()` 这一行没有任何输出。因为你在调用函数的时候，没有给它传递任何值，于是，在函数内部代码执行的时候，`name in names` 的值是 `False`，所以，`for` 循环内部的代码没有被执行。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在函数内部，是把 `names` 这个参数当作容器处理的 —— 否则也没办法用 `for ... in ...` 来处理。而在调用函数的时候，我们是可以将一个容器传递给函数的 Arbitrary Positional Arguments 的 —— 做法是，在调用函数的时候，在参数前面加上星号 `*`："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi, mike!\n",
      "Hi, john!\n",
      "Hi, zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(*names):\n",
    "    for name in names:\n",
    "        print(f'Hi, {name}!')\n",
    "\n",
    "names = ('mike', 'john', 'zeo')\n",
    "say_hi(*names)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实际上，因为以上的 `say_hi(*names)` 函数内部就是把接收到的参数当作容器处理的，于是，在调用这个函数的时候，向它传递任何容器都会被同样处理："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi, P!\n",
      "Hi, y!\n",
      "Hi, t!\n",
      "Hi, h!\n",
      "Hi, o!\n",
      "Hi, n!\n",
      "Hi, 0!\n",
      "Hi, 1!\n",
      "Hi, 2!\n",
      "Hi, 3!\n",
      "Hi, 4!\n",
      "Hi, 5!\n",
      "Hi, 6!\n",
      "Hi, 7!\n",
      "Hi, 8!\n",
      "Hi, 9!\n",
      "Hi, 10!\n",
      "Hi, 9!\n",
      "Hi, 8!\n",
      "Hi, 7!\n",
      "Hi, 6!\n",
      "Hi, 5!\n",
      "Hi, 4!\n",
      "Hi, 3!\n",
      "Hi, 2!\n",
      "Hi, 1!\n",
      "Hi, ann!\n",
      "Hi, mike!\n",
      "Hi, joe!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(*names):\n",
    "    for name in names:\n",
    "        print(f'Hi, {name}!')\n",
    "\n",
    "a_string = 'Python'\n",
    "say_hi(*a_string)\n",
    "\n",
    "a_range = range(10)\n",
    "say_hi(*a_range)\n",
    "\n",
    "a_list = list(range(10, 0, -1))\n",
    "say_hi(*a_list)\n",
    "\n",
    "a_dictionary = {'ann':2321, 'mike':8712, 'joe': 7610}\n",
    "say_hi(*a_dictionary)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "_在定义可以接收一系列值的位置参数时，建议在函数内部为该变量命名时总是用**复数**_，因为函数内部，总是需要 `for` 循环去迭代元组中的元素，这样的时候，名称的复数形式对代码的可读性很有帮助 —— 注意以上程序第二行。以中文为母语的人，在这个细节上常常感觉 “不堪重负” —— 因为中文的名词没有复数 —— 但必须习惯。（同样的道理，若是用拼音命名变量，就肯定是为将来挖坑……）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**注意**：一个函数中，可以接收一系列值的位置参数只能有一个；并且若是还有其它位置参数存在，那就必须把这个可以接收一系列值的位置参数排在所有其它位置参数之后。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, Mike!\n",
      "Hello, John!\n",
      "Hello, Zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(greeting, *names):\n",
    "    for name in names:\n",
    "        print(f'{greeting}, {name.capitalize()}!')\n",
    "\n",
    "say_hi('Hello', 'mike', 'john', 'zeo')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 为函数的某些参数设定默认值"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "可以在定义函数的时候，为某些参数设定默认值，这些有默认值的参数，又被称作关键字参数（Keyword Arguments）。从这个函数的 “用户” 角度来看，这些设定了默认值的参数，就成了 “可选参数”。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, mike!\n",
      "Hello, john!\n",
      "Hello, zeo!\n",
      "Hello, Mike!\n",
      "Hello, John!\n",
      "Hello, Zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(greeting, *names, capitalized=False):\n",
    "    for name in names:\n",
    "        if capitalized:\n",
    "            name = name.capitalize()\n",
    "        print(f'{greeting}, {name}!')\n",
    "\n",
    "say_hi('Hello', 'mike', 'john', 'zeo')\n",
    "say_hi('Hello', 'mike', 'john', 'zeo', capitalized=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 可以接收一系列值的关键字参数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "之前我们看到，可以设定一个位置参数（Positional Argument），接收一系列的值，被称作 “Arbitrary Positional Argument”；\n",
    "\n",
    "同样地，我们也可以设定一个可以接收很多值的关键字参数（Arbitrary Keyword Argument）。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 63,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, mike!\n",
      "Oh, my darling, ann!\n",
      "Hi, john!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(**names_greetings):\n",
    "    for name, greeting in names_greetings.items():\n",
    "        print(f'{greeting}, {name}!')\n",
    "        \n",
    "say_hi(mike='Hello', ann='Oh, my darling', john='Hi')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "既然在函数内部，我们在处理接收到的 Arbitrary Keyword Argument 时，用的是对字典的迭代方式，那么，在调用函数的时候，也可以直接使用字典的形式："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 64,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, mike!\n",
      "Oh, my darling, ann!\n",
      "Hi, john!\n",
      "Hello, mike!\n",
      "Oh, my darling, ann!\n",
      "Hi, john!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(**names_greetings):\n",
    "    for name, greeting in names_greetings.items():\n",
    "        print(f'{greeting}, {name}!')\n",
    "        \n",
    "a_dictionary = {'mike':'Hello', 'ann':'Oh, my darling', 'john':'Hi'}\n",
    "say_hi(**a_dictionary)\n",
    "\n",
    "say_hi(**{'mike':'Hello', 'ann':'Oh, my darling', 'john':'Hi'})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "至于在函数内部，你用什么样的迭代方式去处理这个字典，是你自己的选择："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 65,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, mike!\n",
      "Oh, my darling, ann!\n",
      "Hi, john!\n"
     ]
    }
   ],
   "source": [
    "def say_hi_2(**names_greetings):\n",
    "    for name in names_greetings:\n",
    "        print(f'{names_greetings[name]}, {name}!')\n",
    "say_hi_2(mike='Hello', ann='Oh, my darling', john='Hi')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 函数定义时各种参数的排列顺序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在定义函数的时候，各种不同类型的参数应该按什么顺序摆放呢？对于之前写过的 `say_hi()` 这个函数，"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 66,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi, mike!\n",
      "Hi, john!\n",
      "Hi, zeo!\n",
      "Welcome, Mike!\n",
      "Welcome, John!\n",
      "Welcome, Zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(greeting, *names, capitalized=False):\n",
    "    for name in names:\n",
    "        if capitalized:\n",
    "            name = name.capitalize()\n",
    "        print(f'{greeting}, {name}!')\n",
    "\n",
    "say_hi('Hi', 'mike', 'john', 'zeo')\n",
    "say_hi('Welcome', 'mike', 'john', 'zeo', capitalized=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果，你想给其中的 `greeting` 参数也设定个默认值怎么办？写成这样好像可以："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hi, mike!\n",
      "Hi, john!\n",
      "Hi, zeo!\n",
      "\n",
      "Welcome, Mike!\n",
      "Welcome, John!\n",
      "Welcome, Zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(greeting='Hello', *names, capitalized=False):\n",
    "    for name in names:\n",
    "        if capitalized:\n",
    "            name = name.capitalize()\n",
    "        print(f'{greeting}, {name}!')\n",
    "\n",
    "say_hi('Hi', 'mike', 'john', 'zeo')\n",
    "say_hi('Welcome', 'mike', 'john', 'zeo', capitalized=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "但 `greeting` 这个参数虽然有默认值，可这个函数在被调用的时候，还是必须要给出这个参数，否则输出结果出乎你的想象："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mike, john!\n",
      "mike, zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(greeting='Hello', *names, capitalized=False):\n",
    "    for name in names:\n",
    "        if capitalized:\n",
    "            name = name.capitalize()\n",
    "        print(f'{greeting}, {name}!')\n",
    "\n",
    "say_hi('mike', 'john', 'zeo')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "设定了默认值的 `greeting`，竟然不像你想象的那样是 “可选参数”！所以，你得这样写："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 67,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Hello, mike!\n",
      "Hello, john!\n",
      "Hello, zeo!\n",
      "Hi, mike!\n",
      "Hi, john!\n",
      "Hi, zeo!\n"
     ]
    }
   ],
   "source": [
    "def say_hi(*names, greeting='Hello', capitalized=False):\n",
    "    for name in names:\n",
    "        if capitalized:\n",
    "            name = name.capitalize()\n",
    "        print(f'{greeting}, {name}!')\n",
    "\n",
    "say_hi('mike', 'john', 'zeo')\n",
    "say_hi('mike', 'john', 'zeo', greeting='Hi')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这是因为函数被调用时，面对许多参数，Python 需要按照既定的规则（即，顺序）判定每个参数究竟是哪一类型的参数：\n",
    "\n",
    "> **Order of Arguments**\n",
    "> 1. Positional\n",
    "> 1. Arbitrary Positional\n",
    "> 1. Keyword\n",
    "> 1. Arbitrary Keyword\n",
    "\n",
    "所以，即便你在定义里写成\n",
    "\n",
    "```python\n",
    "def say_hi(greeting='Hello', *names, capitalized=False):\n",
    "    ...\n",
    "```\n",
    "\n",
    "在调用该函数的时候，无论你写的是\n",
    "```python\n",
    "say_hi('Hi', 'mike', 'john', 'zeo')\n",
    "```\n",
    "\n",
    "还是\n",
    "```python\n",
    "say_hi('mike', 'john', 'zeo')\n",
    "```\n",
    "\n",
    "Python 都会认为接收到的第一个值是 Positional Argument —— 因为在定义中，`greeting` 被放到了 Arbitrary Positional Arguments 之前。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  },
  "toc-autonumbering": true
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
